/**
 *  Copyright (c) 2010-2011, Monash e-Research Centre
 * (Monash University, Australia)
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 * * Neither the name of the Monash University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package edu.monash.historyofadoption;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import arc.xml.XmlDoc;

/**
 * Servlet implementation class Submit
 */
public class Submit extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Submit() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.println(Submit.htmlheader);

		out
				.println("<h2>Please enter your Mediaflux domain and credentials!</h2>");
		out.println("<form action='submit' method=POST>");
		out
				.println("<p>Domain: <input type='text' name='domain' size=20 /><br/>");
		out.println("Username: <input type='text' name='user' size=20 /><br/>");
		out
				.println("Password: <input type='password' name='password' size=20 /></p>");
		out
				.println("<p><input type='submit' name='submit' value='Submit' /></p>");
		out.println("</form>");
		out.println(Submit.htmlfooter);
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// put the form here? or look up how to do JSP
		// what's JSP :P
		PrintWriter out = response.getWriter();
		try {
			out.println(Submit.htmlheader);
			// out.println("Hello World");

			InputStream inputStream = Submit.class.getClassLoader()
					.getResourceAsStream("setup.properties");

			Properties properties = new Properties();

			// load the inputStream using the Properties
			properties.load(inputStream);
			// get the value of the property
			String host = properties.getProperty("mediaflux.server.host");
			int port = Integer.parseInt(properties
					.getProperty("mediaflux.server.port"));
			String basecollection = properties
					.getProperty("mediaflux.server.basecollection");
			Boolean useSSL = Boolean.valueOf(properties
					.getProperty("mediaflux.server.useSSL"));
			Boolean encrypt = Boolean.valueOf(properties
					.getProperty("mediaflux.server.encrypt"));

			// RETRIEVE FORM POST VARS
			// String domain = "mflux-dev";
			// String user = "stevea";
			// String password = "mfluxd3v";
			String domain = request.getParameter("domain");
			String user = request.getParameter("user");
			String password = request.getParameter("password");

			MediafluxConfig mfConfig = new MediafluxConfig(host, port, domain,
					user, password, useSSL, encrypt, basecollection);
			try {

				MediafluxClient myMFClient = new MediafluxClient(mfConfig);
				out.println("<h2>Choose collection from which to submit</h2>");
				out.println("Collections under: "
						+ mfConfig.getBasecollection());

				out.println("<form action=\"listAssets\" method=POST>");
				for (XmlDoc.Element namespaceElement : myMFClient
						.getBaseCollectionList()) {
					String namespace = myMFClient
							.getNamespace(namespaceElement);
					String name = getStorytellerName(myMFClient, namespace);
					out
							.println("<p><input type='radio' name='namespace' value='"
									+ namespace
									+ "'> Name: "
									+ name
									+ "<br/>Filename: " + namespace);
					// out.println("<br/>");

					out.println("</p>");
				}
				out.println("<input type='hidden' name='domain' value='"
						+ domain + "' />");
				out.println("<input type='hidden' name='user' value='" + user
						+ "' />");
				out.println("<input type='hidden' name='password' value='"
						+ password + "' />");
				out.println("<input type='submit' value='Continue' />");
				out.println("</form>");

			} catch (Throwable e) {
				out.println("<h1>LOGIN FAILED</h1>");
				out
						.println("<p>Your login credentials may be wrong. Please return to the <a href=\"/HoAConfluenceSubmit/\">login screen</a> and try again</p>");
				e.printStackTrace();
			}

			out.println(Submit.htmlfooter);
			out.close();
		}

		catch (Throwable e) {
			// display stack trace in the browser
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			response.setContentType("text/html");
			e.printStackTrace(printWriter);
			out
					.println("<strong>Oops!</strong><br/><br/>An error has occurred. Technical details are as follows:</br><br/><font face=\"Courier New\" size=\"2\">"
							+ stringWriter.toString() + "</font>");
		}
	}

	public static File createTempDirectory() throws IOException {
		final File temp;

		temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

		if (!(temp.delete())) {
			throw new IOException("Could not delete temp file: "
					+ temp.getAbsolutePath());
		}

		if (!(temp.mkdir())) {
			throw new IOException("Could not create temp directory: "
					+ temp.getAbsolutePath());
		}

		return (temp);
	}

	private static HashMap<String, String> convertMetadataTxt(String input) {
		HashMap<String, String> output = new HashMap<String, String>();
		String[] parameters = input.split("param; name=");
		for (String string : parameters) {
			if (!string.trim().equals("")) {
				String[] par = string.split(", value=");
				output.put(par[0].trim(), par[1].trim());
			}
		}
		return output;
	}

	private String getStorytellerName(MediafluxClient client, String namespace)
			throws Throwable {	
		String name = "Name not found";
		Collection<XmlDoc.Element> finditassetlist = client
				.getAssetList(namespace);
		Iterator<XmlDoc.Element> findit = finditassetlist.iterator();
		while (findit.hasNext()) {
			XmlDoc.Element e = (XmlDoc.Element) findit.next();

			String assetName = client.getAssetName(e);
			if (assetName == null) continue;
			if (assetName.equals("metadata.txt")) {
				String assetId = client.getAssetId(e);
				byte[] data = client.getAssetContents(assetId).bytearray();
				String metadata = new String(data);
				HashMap<String, String> pars = convertMetadataTxt(metadata);
				name = pars.get("participant_name") + " "
						+ pars.get("participant_surname");
			}
		}
		return name;
	}

	private static final String htmlheader = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" "
			+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> "
			+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"de\" xml:lang=\"en\">"
			+ " <head>  <title>Submit story to Confluence</title>  "
			+ "<META name=\"robots\" content=\"noindex,nofollow\">"
			+ "<LINK href=\"static/form-style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\">"
			+ "</head> "
			+ "<body>"
			+ "<DIV id=\"header\">"
			+ "<H1>History of Adoption in Australia</H1>"
			+ "<DIV id=\"logos\"><IMG src=\"static/logo-monash.jpg\" alt=\"Monash University logo\" "
			+ "name=\"logo_monash\" width=\"208\" height=\"34\" id=\"logo_monash\"><BR>"
			+ " <IMG src=\"static/acu-logo.jpg\" width=\"248\" height=\"35\" "
			+ "alt=\"Australian Catholic University logo\" id=\"logo_acu\"></DIV>"
			+ "<DIV class=\"clear_both\"></DIV>"
			+ "</DIV>"
			+ "<DIV id=\"content\"> ";
	private static final String htmlfooter = " </div> </body> </html> ";
}
